class EditorManager {
    static tempItemListElement = null;//临时存储是哪个元素调出的项目列表
    //测试用
    static url = "./testData/"
    // static url = ".。/data/"

    //未保存缓存数据
    static cache = {}

    /**
     * 输出data
     */
    static exportData() {
        const form = layui.form;
        const table = layui.table;

        const info = form.val("info");
        const {id, name} = info;
        const affixLists = table.getData("pool");
        // console.log({id, name, affixLists})
        return {id, name, affixLists};
    }

    /**
     * 加载所有数据
     * @returns {Promise<void>}
     */
    static async loadAllData() {
        await Promise.all([
            this.loadAffixesData(),
            this.loadAffixesPoolsData(),
        ])
        this.setItemList();
    }

    /**
     * 加载词条数据
     * @returns {Promise<void>}
     */
    static async loadAffixesData() {
        const response = await fetch(`${this.url}EquipAffixes.json`);
        if (response.ok) {
            this.affixesData = await response.json();
        } else {
            alert("未找到EquipAffixes.json文件,请确认编辑器目录是否放置在rm工程跟目录下");
        }
    }

    /**
     * 加载词条池数据
     * @returns {Promise<void>}
     */
    static async loadAffixesPoolsData() {
        const response = await fetch(`${this.url}EquipAffixPools.json`);
        if (response.ok) {
            this.data = await response.json();
        } else {
            alert("未找到EquipAffixPools.json文件,请确认编辑器目录是否放置在rm工程跟目录下");
        }
        this.addDisplayParam();
    }

    /**
     * 添加表格说明属性
     */
    static addDisplayParam() {
        for (const item of this.data) {
            if (!item) continue;
            const {affixLists} = item;
            for (const affix of affixLists) {
                const {affixs, chance} = affix;
                if (!!affixs && !!chance) {
                    const display = affixs.map(item => {
                        return `${item}:${this.affixesData[item].name}`
                    });
                    const rate = `${chance * 100}%`;
                    affix.display = display;
                    affix.rate = rate;
                }
            }
        }
    }

    /**
     * 根据data设置项目id查询页面树列表
     */
    static setItemList() {
        const affixesData = this.affixesData.filter(item => !!item?.name);
        // const num = affixesData.length - 1;
        const pageNum = Math.ceil(affixesData.length / 100);
        let list = [], skillList = [];
        for (let i = 1; i <= pageNum; i++) {
            const children = [];
            //开始索引
            const start = (i - 1) * 100;
            //结束索引
            const end = i * 100;
            const title = `${start + 1}-${end}`;
            const id = `page-${i}`
            const obj = {title, id, children}
            //添加分页的数据
            for (let j = 0; j <= 100; j++) {
                const index = (i - 1) * 100 + j;
                const affix = affixesData[index];
                if (!!affix) {
                    const name = affix.name;
                    const id = `${affix.id}:${name}`;
                    const title = `${affix.id}:${name}`;
                    const obj = {title, id};
                    children.push(obj);
                }
            }
            list.push(obj);
        }
        layui.use(function () {
            const tree = layui.tree;
            const form = layui.form;
            const layer = layui.layer;
            const $ = layui.$;
            // 渲染
            tree.render({
                elem: '#ID-tree-item-affix-list',
                data: [{"title": "词条", "id": "affixList", "children": list}],
                click: function (obj) {
                    if (!!obj.data.children) return;
                    const value = EditorManager.tempItemListElement.value;
                    EditorManager.tempItemListElement.value += value === "" ? `${obj.data.id}` : `,${obj.data.id}`;
                    EditorManager.tempItemListElement = null;
                    layer.close(EditorManager.tempLayerIndex);
                    EditorManager.tempLayerIndex = null;
                }
            })
            // 特性输入框点击打开项目选择窗口
            form.on('input-affix(affixsClick)', function (data) {
                EditorManager.tempItemListElement = document.getElementById(`affix-show`);
                EditorManager.tempLayerIndex = layer.open({
                    title: "项目列表",
                    type: 1,
                    area: ['500px', '80%'],
                    content: $('#ID-layer-item-affix-list')
                })
            })
        })
    }

    /**
     * 初始化目录
     */
    static initDirectory() {
        //获取目录容器
        const container = document.getElementById("directory");
        //以100为单位分割总项目，计算页数
        const pageNum = Math.ceil(this.data.length / 100);
        //按页
        for (let i = 1; i <= pageNum; i++) {
            //开始索引
            const start = (i - 1) * 100;
            //结束索引
            const end = i * 100;
            const li = document.createElement("li");
            const title = document.createElement("div");
            const list = document.createElement("ul");
            li.className = "layui-menu-item-group";
            title.className = "layui-menu-body-title";
            title.innerHTML = `${start + 1}-${end}`;
            li.appendChild(title);
            li.appendChild(list);
            container.appendChild(li);
            //添加每页的数据
            for (let j = 1; j <= 100; j++) {
                const no = (i - 1) * 100 + j;
                if (!this.data[no]) continue;
                const name = `ID-${no}-${this.data[no]?.name}`;
                const li = document.createElement("li");
                const item = document.createElement("div");
                const a = document.createElement("a");
                li.setAttribute("lay-options", `{index: ${no}}`);
                li.id = `d-index-${no}`;
                item.className = "layui-menu-body-title";
                a.href = "javascript:void(0);";
                a.innerHTML = name;
                item.appendChild(a);
                li.appendChild(item);
                list.appendChild(li);
            }
        }
        this.renderDirectory();
    }

    /**
     * 渲染目录
     */
    static renderDirectory() {
        //动态生成的目录所以需要重新渲染
        // layui.element.render();
        layui.use(function () {
            const dropdown = layui.dropdown;
            //目录点击事件
            dropdown.on('click(directory)', function (options) {
                //面板存入临时数据
                const tempData = EditorManager.exportData();
                const {id, name} = tempData
                if (id !== "") EditorManager.cache[id] = tempData;
                const {index} = options;
                //更新显示面板
                const newData = EditorManager.cache[index] ?? EditorManager.data[index];
                EditorManager.updatePanel(newData);
            })
        })
    }

    /**
     * 更新面板
     * @param {Object} data 装备词条数据
     */
    static updatePanel(data) {
        const {id, name, affixLists} = data;
        const form = layui.form;
        const table = layui.table;
        form.val("info", {id, name});
        table.reloadData("pool", {
            data: affixLists
        })
    }

    /**
     * 渲染所有
     */
    static renderAll() {
        this.renderTable();
        this.addEleEvent();
    }

    /**
     * 渲染表格
     */
    static renderTable() {
        layui.use('table', function () {
            const table = layui.table;
            const layer = layui.layer;
            //layui需要手动引入jq
            const $ = layui.$;
            // 已知数据渲染
            table.render({
                elem: '#ID-table-pool',
                toolbar: true,
                defaultToolbar: [{
                    title: '增加',
                    layEvent: 'addParam',
                    icon: 'layui-icon-addition',
                    onClick: function (data) {
                        //清空之前属性输入
                        window["affix-show"].value = "";
                        window["affixChance"].value = "";
                        layer.open({
                            title: "词条设置",
                            type: 1,
                            area: ['500px', '350px'],
                            content: $('#ID-layer-affix'),
                            btn: ["确认"],
                            btn1: function (index, layero, that) {
                                const display = document.getElementById("affix-show").value;
                                const rateValue = document.getElementById("affixChance").value
                                if (display === "" || rateValue === "") {
                                    layer.msg("词条列表或概率不能为空");
                                    return false;
                                }
                                const rate = `${rateValue}%`;
                                const chance = Number(rateValue) / 100;
                                const affixs = display.split(",").map(item => {
                                    return item.split(":")[0];
                                })
                                table.reloadData("pool", {
                                    data: [...table.getData("pool"), {display, rate, chance, affixs}]
                                })
                                layer.close(index);
                            }
                        })
                    }
                }, {
                    title: '清空',
                    layEvent: 'clearParam',
                    icon: 'layui-icon-delete',
                    onClick: function (obj) {
                        //清空表格数据
                        layui.table.reloadData("pool", {
                            data: []
                        })
                    }
                }],
                id: "pool",
                css: [ // 设置单元格样式
                    // 取消默认的溢出隐藏，并设置适当高度
                    '.layui-table-cell{height: 50px; line-height: 40px;}',
                    '.layui-table-cell .layui-colorpicker{width: 38px; height: 38px;}',
                    '.layui-table-cell select{height: 36px; padding: 0 5px;}'
                ].join(''),
                cols: [[
                    //隐藏数据
                    // {field: 'affixs', title: '词条组'},
                    // {field: 'chance', title: '出现概率', width: 120},
                    {field: 'display', title: '词条组'},
                    {field: 'rate', title: '出现概率', width: 120},
                    {fixed: 'right', title: '操作', width: 150, minWidth: 150, toolbar: '#tableBar'}
                ]],
                data: []
            })
            // 触发单元格工具删除事件
            table.on('tool(pool)', function (obj) { // 双击 toolDouble
                // var data = obj.data; // 获得当前行数据
                const tableIndex = obj.index;
                if (obj.event === 'del') {
                    obj.del();
                } else if (obj.event === 'edit') {
                    window["affix-show"].value = "";
                    window["affixChance"].value = "";
                    layer.open({
                        title: "词条修改",
                        type: 1,
                        area: ['500px', '350px'],
                        content: $('#ID-layer-affix'),
                        btn: ["修改"],
                        btn1: function (index, layero, that) {
                            const display = document.getElementById("affix-show").value;
                            const rateValue = document.getElementById("affixChance").value
                            if (display === "" || rateValue === "") {
                                layer.msg("词条列表或概率不能为空");
                                return false;
                            }
                            const rate = `${rateValue}%`;
                            const chance = Number(rateValue) / 100;
                            const affixs = display.split(",").map(item => {
                                return item.split(":")[0];
                            })
                            table.updateRow("pool", {
                                index: tableIndex,
                                data: {display, rate, chance, affixs}
                            })
                            layer.close(index);
                        }
                    })
                }
            })
        })
    }

    /**
     * 添加页面元素事件
     */
    static addEleEvent() {
        //底部按钮逻辑
        layui.use(function () {
            const layer = layui.layer;
            const util = layui.util;
            // 事件
            util.on('lay-on', {
                'changeMax': function () {
                    layer.prompt({title: '请输入最大值'}, function (value, index, elem) {
                        if (value === '') return elem.focus();
                        EditorManager.changeItemMax(value);
                        layer.close(index);
                    });
                },
                'saveToFile': function () {
                    EditorManager.saveToFile();
                }
            })
        })
        //词条名输入监听
        const input = document.getElementById("poolName");
        input.addEventListener("input", (e) => {
            EditorManager.upDateName(e);
        })
    }

    /**
     * 更新目录列表名称
     */
    static upDateName(e) {
        const value = e.target.value;
        const {id} = layui.form.val("info");
        if (!id) return;
        const li = document.getElementById(`d-index-${id}`);
        li.innerHTML = `ID-${id}-${value}`;
    }

    /**
     * 更改目录最大值
     * @param {number} value 最大值
     */
    static changeItemMax(value) {
        const layer = layui.layer;
        const input = Number(value);
        if (!!input) {
            const num = Math.min(input, 1000);
            const data = [null];
            for (let i = 1; i <= num; i++) {
                //优先缓存
                data[i] = this.cache[i] ?? this.data[i] ?? this.nullData(i);
            }
            this.data = data;
            // this.save();
            this.refreshDirectory();
            return;
        }
        layer.msg("输入不合法");
    }

    /**
     * 空数据对象
     * @param {number} id id
     */
    static nullData(id) {
        const name = "";
        const affixLists = [];
        return {id, name, affixLists};
    }

    /**
     * 刷新目录
     */
    static refreshDirectory() {
        //获取目录容器
        const container = document.getElementById("directory");
        container.innerHTML = "";
        this.initDirectory();
    }

    /**
     * 保存数据
     */
    static save() {
        //暂存当前面板数据
        const tempData = EditorManager.exportData();
        const {id} = tempData;
        if (!!id) {
            EditorManager.cache[id] = tempData;
        }
        const data = [null];
        for (let i = 1; i < this.data.length; i++) {
            data[i] = this.cache[i] ?? this.data[i] ?? this.nullData(i);
            //去掉特性data中的解释性属性
            const {affixLists} = data[i];
            for (const item of affixLists) {
                    if (!!item.display) delete item.display;
                    if (!!item.rate) delete item.rate;
            }
        }
        this.data = data;
    }

    /**
     * 保存到文件
     */
    static saveToFile() {
        this.save();
        const fileName = `EquipAffixPools${Date.now()}.json`;
        const data = JSON.stringify(this.data, null, 2);
        if (!!window.require) {
            //nw环境
            const fs = require("fs");
            try {
                //防止有bug文件名加了时间戳暂时不覆盖
                fs.writeFileSync(`${this.url}${fileName}`, data);
            } catch (err) {
                console.log(err);
            }
        } else {
            //浏览器环境
            const blob = new Blob([data], {type: "text/json"});
            const a = document.createElement("a");
            a.download = `${fileName}`;
            a.style.display = "none";
            a.href = URL.createObjectURL(blob);
            a.click();
        }
    }
}